import sqlite3, datetime, glob, sys, os

TMPFILENAME = "/tmp/parsesms.mddata"

#choose the correct file
backups = glob.glob("/Users/*/Library/Application Support/MobileSync/Backup/*/3d0d7e5fb2ce288813306e4d4636395e047a3d28.mddata")
for i in range(len(backups)):
    aPath = backups[i].split(os.path.sep)
    print "%d. %s"% (i+1, aPath[7])
print >> sys.stderr, "Choose your iphone device id? [1-%d]"%len(backups)
line = sys.stdin.readline()
index = int(line)-1
filename = backups[index]

#copy the file, to avoid corrupting it
fromfile = open(filename, "r")
tofile = open(TMPFILENAME, "w")
while fromfile:
    data = fromfile.read(8192)
    if len(data) == 0:
        break
    tofile.write(data)
fromfile.close()
tofile.close()

conn = sqlite3.connect(TMPFILENAME)
c = conn.cursor()
c.execute("select address, text, flags, date from message order by date")
sms = {}
for row in c:
    address = row[0]
#correct some addresses
    if not address:
        continue
    if address[0] == u"0":
        address = "+31%s"%address[1:]
    if address[0:2] == u"31":
        address = "+%s"%address
#all not standard smsses are being filtered out
    if address[0] != u"+":
        continue
    message = row[1]
    direction = ("to", "from")[row[2] & 1]
    date = datetime.datetime.fromtimestamp(row[3])
    
    if not sms.has_key(address):
        sms[address] = []
    sms[address].append({"date": date, "message": message, "direction": direction})

for address in sorted(sms.keys()):
    print address
    for item in sms[address]:
        datestring = item["date"].strftime("%A %d %B %Y %H:%M:%S")
        if item["direction"] == "from":
            print ">>>>>>>>>>>>>>>>>>>>>>>>>> %s" % datestring
        else:
            print "<<<<<<<<<<<<<<<<<<<<<<<<<< %s" % datestring
        if item["message"]:
            print item["message"].encode("utf-8")
        print 
    print "\n"
